package com.lq.learningTest.Socket;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpTest {
    @Test
    public void serverTest() throws IOException {
        // 创建ServerSocket
        ServerSocket server = new ServerSocket();
        // 绑定在某一个端口上，这里不需要使用InetAddress.getLoopbackAddress()，服务端不需要关心ip地址
        server.bind(new InetSocketAddress(8888));
        // 监听在这个端口,这是一个阻塞的方法
        Socket socket = server.accept();

        InputStream inputStream = socket.getInputStream();

        byte[] buffer = new byte[1024 * 1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1){
            System.out.println(new String(buffer,0,len));
        }
        inputStream.close();
        socket.close();
    }

    @Test
    public void clientTest() throws IOException {
        // 创建Socket
        Socket socket = new Socket();
        // 使用这个socket进行连接，客户端需要ip:端口，加上InetAddress.getLoopbackAddress()环回地址用于测试
        socket.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(),8888));

        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello server!".getBytes());

        outputStream.close();
        inputStream.close();
        socket.close();

    }
}
